package com.wwmz.cloud.many.source.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

/**
 * created by wumz
 */
@Configuration             //此处指向DAO接口
@MapperScan(basePackages = "com.example.dao.merchant", sqlSessionTemplateRef  = "merchantSqlSessionTemplate")
public class MerchantDataSourceConfig {

    @Bean(name = "merchantDataSource") //此处指向yml配置文件中具体的数据源
    @ConfigurationProperties(prefix = "spring.datasource.merchant")
    public DataSource testDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "merchantSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("merchantDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/merchantDB/*.xml"));//指定mapper.xml路径
        //增加驼峰配置
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

    @Bean(name = "merchantTransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("merchantDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "merchantSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("merchantSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
